package chances.epg.navigator.tag;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;

import chances.epg.commons.utils.PathUtils;
import chances.epg.commons.utils.SpringWebUtils;
import chances.epg.config.BaseMvcConfig;
import chances.epg.navigator.EpgConstants;
import chances.epg.navigator.context.AccessContext;
import chances.epg.navigator.history.NavigateHistory;
import chances.epg.navigator.history.NavigateHistoryFactory;
import chances.epg.session.UserSession;
import chances.epg.session.UserSessionHelper;

public class HistoryTag extends TagSupport {

	private static final long serialVersionUID = -4405274277767004085L;

	private String var;

	private AccessContext _context;

	private boolean isNeedhost;

	private String pop;

	@Override
	public int doEndTag() throws JspException {
		System.out.println("in HistoryTag===========================================");
		if (_context == null) {
			_context = (AccessContext) pageContext.findAttribute(EpgConstants.EPG_CONTEXT);
		}
		if (_context == null) {
			return SKIP_BODY;
		}
		UserSession userSession = UserSessionHelper.getUserSession(pageContext);
		if (userSession == null) {
			return SKIP_BODY;
		}
		HttpServletRequest httpRequest = (HttpServletRequest) pageContext.getRequest();
		NavigateHistory history = NavigateHistoryFactory.getHistory(httpRequest, userSession);

		if (StringUtils.isNotEmpty(this.pop)) {
			this.popHistory(history);
		}
		String path = history.getLastPath();
		if (this.isNeedhost) {
			path = checkUrl(path);
		}
		pageContext.setAttribute(var, path);
		return super.doEndTag();
	}

	private void popHistory(NavigateHistory history) {
		if (this.pop.equals("-1")) {
			System.out.println("history.size:"+(history.size() - 1));
			history.pop(history.size() - 1);
		} else {
			try {
				history.pop(Integer.parseInt(this.pop));
			} catch (Exception e) {
			}
		}

	}

	private String checkUrl(String path) {
		if (path.indexOf("/") == 0 && this.isNeedhost) {
			HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
			BaseMvcConfig baseMvcConfig = SpringWebUtils.findBean(pageContext, BaseMvcConfig.class);
			String host = baseMvcConfig.getEpgHost();
			path = PathUtils.join(host, path.replace(request.getContextPath(), ""));
		}
		return path;
	}

	public void setVar(String var) {
		this.var = var;
	}

	public void setAccessContext(Object obj) {
		if (AccessContext.class.isInstance(obj)) {
			this._context = (AccessContext) obj;
		}
	}

	public boolean isNeedhost() {
		return isNeedhost;
	}

	public void setIsNeedhost(boolean isNeedhost) {
		this.isNeedhost = isNeedhost;
	}

	public String getPop() {
		return pop;
	}

	public void setPop(String pop) {
		this.pop = pop;
	}

}
